<?php
/**
 * PublicController.class.php
 * 公共控制器
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2017-08-25
 */

namespace Attach\Controller;
use Wechat\Util\WechatExt;

class WechatController extends BaseController {

    public $Wechat;

    function __construct(){
        parent::__construct();

        //变量注册
        $this->Wechat   = WechatExt::getInstance();
    }

    /**
     * 获取Oauth登录信息
     * @return $url and $flag
     */
    function getOauthData(){
        $flag  = strtoupper(md5(time().'/'.rand(1000, 9999)));
        $url    = $this->Wechat->getOauthRedirect(C('SERVER_NAME').'/server/index.php/Attach/Wechat/registerOauth?flag='.$flag);
        $result     = [
            'url'   => $url,
            'flag'  => $flag
        ];

        $this->response($result);
    }

    /**
     * 注册Oauth信息
     * @param   $flag and $code
     * @return  view of boolean
     */
    function registerOauth(){
        $client     = $this->unEmptyParams(['code', 'flag']);
        $wxOauth    = $this->Wechat->getOauthAccessToken();
        if(!$wxOauth){
            // echo '微信授权失败!';
            $this->display('error');
            exit;
        }
        
        //授权信息记录缓存
        S($this->prefixOauthCache.$client['flag'], $wxOauth, 600);
        // echo $this->prefixOauthCache.$client['flag'];
        // dump($wxOauth);

        $this->display('success');
        //登录成功界面
        //To do...
    }

    /**
     * 验证微信Oauth登录信息
     * @param   $flag
     * @return  boolean
     */
    function verifyOauth(){
        $client     = $this->unEmptyParams(['flag']);
        $wxOauth    = S($this->prefixOauthCache.$client['flag']);
        if(!$wxOauth){
            $this->response('未扫码!', -503);
        }

        //用户信息获取
        $userInfo   = D('User')->getItem([
            'open_id'   => $wxOauth['openid'],
            'status'    => 1
        ]);
        if(!$userInfo){
            $this->response('用户不存在', -504);
        }
        if(!in_array($userInfo['role_id'], [101, 102, 103, 104])){
            $this->response('非推广人员角色不可登录', -505);
        }

        //用户ID存储session
        session('user_id', $userInfo['id']);

        $this->response(['info' => $userInfo]);
    }

    function debug(){
        $this->display('error');
    }

}